package com.ncloud.crm.service.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ncloud.common.enmus.ResultEnum;
import com.ncloud.common.exception.UserException;
import com.ncloud.crm.common.Constant;
import com.ncloud.crm.entity.BsPublicCloud;
import com.ncloud.crm.entity.order.WorkNodeCloudIpseg;
import com.ncloud.crm.entity.order.WorkNodePublicCloud;
import com.ncloud.crm.mapper.WorkNodePublicCloudMapper;
import com.ncloud.crm.service.BsPublicCloudService;
import com.ncloud.crm.service.WorkNodePublicCloudSegService;
import com.ncloud.crm.service.WorkNodePublicCloudService;
import com.ncloud.crm.utils.DateUtils;
import com.ncloud.crm.utils.OrderNodeDefineUtils;
import com.ncloud.crm.utils.TableIdDefineUtils;
import com.ncloud.param.service.SequenceService;

/**
 * Created by shiqiang on 2017/4/17.
 */
@Service
public class WorkNodePublicCloudServiceImpl implements WorkNodePublicCloudService {
    private static final Logger logger = LogManager.getLogger(WorkNodePublicCloudServiceImpl.class);
    @Autowired
    private WorkNodePublicCloudMapper workNodePublicCloudMapper;
    @Autowired
    private BsPublicCloudService bsPublicCloudService;
    @Autowired
    private WorkNodePublicCloudSegService workNodePublicCloudSegService;
    @Reference
    private SequenceService sequenceService;
    
    @Override
    public JSONObject getPk(JSONObject json) {
        return null;
    }

    @Override
    public JSONObject insert(JSONObject json) {
        WorkNodePublicCloud workNodePublicCloud = JSON.parseObject(json.toJSONString(),WorkNodePublicCloud.class);
        try {
            validation(workNodePublicCloud);
            workNodePublicCloudMapper.insertWorkNodePublicCloud(workNodePublicCloud);
        }catch (RuntimeException e){
            e.printStackTrace();
            throw new UserException(ResultEnum.DATABASE_ERROR);
        }
        return json;
    }

    @Override
    public JSONObject validate(JSONObject json,JSONObject result) {
        JSONObject jsonObject = new JSONObject();
        return jsonObject;
    }

    private void validation(WorkNodePublicCloud workNodePublicCloud){
        if(workNodePublicCloud.getCloudId() == null){
            Long id = sequenceService.getSequence("seq_eqpt_id");
            workNodePublicCloud.setCloudId(id);
        }

    }
    /*返回云信息下的关联信息*/
    @Override
    public JSONObject eqptPublicCloud(JSONObject node,JSONObject result,JSONArray array){
        JSONObject other = new JSONObject();
        WorkNodePublicCloud workNodePublicCloud =new WorkNodePublicCloud();
        //处理节点设备 3:公有云
        if(node.containsKey("cloud") && Constant.NODE_TYPE_0.equals(node.getString("nodeType"))
                && Constant.NODE_TYPE_CLOUD_VPC_0.equals(node.getString("nodeSubType"))){
            JSONObject equipJson = node.getJSONObject("cloud");
            workNodePublicCloud = JSON.parseObject(equipJson.toJSONString(),WorkNodePublicCloud.class);
                /*设置云类型信息*/
            if(StringUtils.isEmpty(workNodePublicCloud.getCloudType())){
                workNodePublicCloud.setCloudType(Constant.CLOUD_TYPE_JD);
            }

//newNodeId
            String eqptModifyTag = workNodePublicCloud.getModifyTag();
            if(StringUtils.isEmpty(eqptModifyTag)){
                eqptModifyTag =node.getString("modifyTag");
                equipJson.put("modifyTag",eqptModifyTag);
            }
            workNodePublicCloud.setModifyTag(eqptModifyTag);
            if(workNodePublicCloud.getNodeId() == null){
                workNodePublicCloud.setNodeId(result.getLong(TableIdDefineUtils.NODE_ID));
            }
            workNodePublicCloud.setWorkId(result.getLong(TableIdDefineUtils.WORK_ID));
            if(Constant.ADD.equals(eqptModifyTag)){

								/*生成设备id*/
                Long id = sequenceService.getSequence("seq_eqpt_id");
                                /*设置云设备主键*/
                workNodePublicCloud.setCloudId(id);
                result.put(TableIdDefineUtils.CLOUD_ID,id);
                workNodePublicCloud.setBeginDate(DateUtils.parseDate(result.getString("createDate")));
                workNodePublicCloud.setEndDate(DateUtils.parseDate(Constant.END_DATE));
                workNodePublicCloud.setUpdateTime(DateUtils.parseDate(result.getString("createDate")));
                workNodePublicCloud.setUpdateUser(result.getLong("userID"));
            }else if(Constant.UPDATE.equals(eqptModifyTag)){
								/*根据修改的节点查询对应的实例信息，对实例做旧单操作，对改单做新增操作*/
                if(workNodePublicCloud.getCloudId() != null){
                    BsPublicCloud bsPublicCloud = bsPublicCloudService.getNodeCloudInfoByPk(workNodePublicCloud.getCloudId());
                    logger.debug("旧public_cloud信息："+JSON.toJSONString(bsPublicCloud));
                    WorkNodePublicCloud workNodePublicCloudOld = JSON.parseObject(JSON.toJSONString(bsPublicCloud),WorkNodePublicCloud.class);

								/*旧记录*/
                    workNodePublicCloudOld.setEndDate(DateUtils.parseDate(result.getString("createDate")));
                    workNodePublicCloudOld.setUpdateTime(DateUtils.parseDate(result.getString("createDate")));
                    workNodePublicCloudOld.setUpdateUser(result.getLong("userID"));
                    workNodePublicCloudOld.setWorkId(result.getLong(TableIdDefineUtils.WORK_ID));
                    workNodePublicCloudOld.setModifyTag(Constant.DEL);
								/*新记录*/
                   /* if(workNodePublicCloud.getNodeId() == null){
                        workNodePublicCloud.setNodeId(result.getLong(TableIdDefineUtils.NODE_ID));
                    }
                    workNodePublicCloud.setWorkId(result.getLong(TableIdDefineUtils.WORK_ID));*/
                    workNodePublicCloud.setBeginDate(DateUtils.parseDate(result.getString("createDate")));
                    workNodePublicCloud.setEndDate(DateUtils.parseDate(Constant.END_DATE));
                    workNodePublicCloud.setUpdateTime(DateUtils.parseDate(result.getString("createDate")));
                    workNodePublicCloud.setUpdateUser(result.getLong("userID"));
                    workNodePublicCloud.setModifyTag(Constant.ADD);
                   // workNodePublicCloud.setNodeInstId(result.getLong("newNodeInstId"));
									/*保存原来信息*/
                    array.add(JSON.parseObject(JSON.toJSONString(workNodePublicCloudOld)));
                }else {
                    throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"公有云信息节点cloudId不存在!");
                }

            }else if(Constant.DEL.equals(eqptModifyTag)){
                workNodePublicCloud.setEndDate(DateUtils.parseDate(result.getString("createDate")));
                workNodePublicCloud.setUpdateTime(DateUtils.parseDate(result.getString("createDate")));
                workNodePublicCloud.setUpdateUser(result.getLong("userID"));
            }else{
                workNodePublicCloud.setUpdateTime(DateUtils.parseDate(result.getString("createDate")));
                workNodePublicCloud.setUpdateUser(result.getLong("userID"));
            }
            //保存节点
            array.add(JSON.parseObject(JSON.toJSONString(workNodePublicCloud)));

            /*处理ip段信息*/
            JSONArray segArray = workNodePublicCloudSegService.validate(equipJson,result);
            if(segArray != null && segArray.size()>0){
                other.put(OrderNodeDefineUtils.PUBLIC_CLOUD_SEG,segArray);
            }
        }
        return other;
    }

	@Override
	public List<WorkNodePublicCloud> getListByWorkId(Long workId) {
		return workNodePublicCloudMapper.getListByWorkId(workId);
	}

	@Override
	public JSONObject getNewListByWorkId(Long workId, Long nodeId) {
        JSONObject result = new JSONObject();
		List<WorkNodePublicCloud> cloud= workNodePublicCloudMapper.getNewListByWorkId(workId,nodeId);
		//JSONArray cloudArray = new JSONArray();
		for (WorkNodePublicCloud workNodePublicCloud : cloud) {
			List<WorkNodeCloudIpseg> ipsegs = workNodePublicCloudSegService.getNewIpSegsByCloudId(workId,workNodePublicCloud.getCloudId());
			
			JSONObject cloudJson = JSON.parseObject(JSON.toJSONString(workNodePublicCloud,SerializerFeature.WriteMapNullValue),Feature.IgnoreNotMatch);
			cloudJson.put("ipseg", JSON.parseArray(JSON.toJSONString(ipsegs,SerializerFeature.WriteMapNullValue)));
			result = cloudJson;
			//cloudArray.add(cloudJson);
		}
		return result;
	}
}
